import Loading from "../controls/loading";
import menu from "./../menu.json";
import {importScript} from "./helper";

const util = {
    getMenu(key) {
        return menu.find(item => item.key === key);
    },
    getMenuLink(key) {
        let target = this.getMenu(key);
        if (target) {
            return target.link;
        } else {
            return "";
        }
    }
};

const MAP = {
    user: {
        pathName: util.getMenuLink("myLogin"),
        indexURL: util.getMenuLink("myIndex"),
        loginURL: "/api/lgb/app/login1",
        loginPath: "/",
        navigator: [
            {name: "我的支部", icon: "01", link: util.getMenuLink("myLodge")},
            {name: "我的大学", icon: "16", link: util.getMenuLink("myCourse")},
            {name: "正能量", icon: "03", link: util.getMenuLink("myPower")},
            {name: "工作简报", icon: "09", link: util.getMenuLink("myBrief")},
            {name: "在线学习", icon: "14", link: util.getMenuLink("myStudy")},
            {name: "医疗健康", icon: "15", link: util.getMenuLink("myMedical")},
            {name: "我的生活", icon: "11", link: util.getMenuLink("myLife")},
            {name: "便捷服务", icon: "10", link: util.getMenuLink("myShortcut")}
        ],
        footer: [
            {title: "首页", icon: "home", active: false, link: util.getMenuLink("myIndex")},
            {title: "通讯录", icon: "contact", active: false, link: util.getMenuLink("myContacts")},
            {title: "通知公告", icon: "notice", active: false, link: util.getMenuLink("myNotice")},
            {title: "设置", icon: "setting", active: false, link: util.getMenuLink("mySetting")}
        ]
    },
    admin: {
        pathName: util.getMenuLink("adminLogin"),
        indexURL: util.getMenuLink("adminIndex"),
        loginURL: "/api/admin/user/login1",
        loginPath: "/admin",
        navigator: [
            {name: "支部建设", icon: "01", link: util.getMenuLink("adminLodge")},
            {name: "离退休干部信息", icon: "12", link: util.getMenuLink("adminLgb")},
            {name: "老年大学", icon: "02", link: util.getMenuLink("adminCourse")},
            {name: "服务管理", icon: "13", link: util.getMenuLink("adminMatter")},
            {name: "医疗健康", icon: "05", link: util.getMenuLink("adminMedical")},
            {name: "走访慰问", icon: "06", link: util.getMenuLink("adminInterview")},
            {name: "学习资料", icon: "08", link: util.getMenuLink("adminStudy")},
            {name: "工作简报", icon: "09", link: util.getMenuLink("adminBrief")}
        ],
        footer: [
            {title: "首页", icon: "home", active: false, link: util.getMenuLink("adminIndex")},
            {title: "通讯录", icon: "contact", active: false, link: util.getMenuLink("adminContacts")},
            {title: "通知公告", icon: "notice", active: false, link: util.getMenuLink("adminNotice")},
            {title: "设置", icon: "setting", active: false, link: util.getMenuLink("adminSetting")}
        ]
    }
};

const WhiteList = [
    "/api/lgb/app/lgb/branchcheckin/getByDept",
    '/api/lgb/app/lgb/getAccessToken',
    "/api/lgb/app/lgb/branchcheckin/getByPerson"
];

const User = {
    info: null,
    setRequestTransformer(view, router, request) {
        let loginInfo = this.getUserMap();
        if (!this.getToken()) {
            router.open(loginInfo.loginPath);
        }
        request.addRequestTransformer((ops) => ops.headers.ttsx_auth_token = this.getToken());
        request.addRequestTransformer(ops => {
            if (this.isAdmin()) {
                let has = WhiteList.find(item => ops.url.indexOf(item) === 0);
                if (ops.url.indexOf('/api/lgb/app/') === 0 && !has) {
                    ops.url = '/api/admin/' + ops.url.substring(13);
                }
            }
        });
        request.addResponseTransformer((response, data) => {
            if (data.code === "2") {
                router.open(loginInfo.loginPath);
            }
            return data;
        });
    },
    getBaseInfo() {
        if (!this.info) {
            this.info = window.localStorage.baseInfo ? JSON.parse(window.localStorage.baseInfo) : {};
        }
        return this.info;
    },
    getUserInfo() {
        if (this.isAdmin()) {
            return this.getBaseInfo();
        } else {
            return this.getBaseInfo().userInfo;
        }
    },
    getToken() {
        return this.getBaseInfo().token || "";
    },
    isAutoLogin() {
        return this.getBaseInfo().a === true;
    },
    save(info) {
        window.localStorage.baseInfo = JSON.stringify(info);
        this.info = Object.assign(this.info || {}, info);
    },
    getIndexMap() {
        return MAP[Reflect.ownKeys(MAP).find(type => MAP[type].indexURL === window.location.pathname)];
    },
    getUserMap() {
        if (window.location.pathname !== "/") {
            if (window.location.pathname.indexOf("/my") === 0) {
                return MAP.user;
            } else {
                return MAP.admin;
            }
        } else {
            return MAP.user;
        }
    },
    isAdmin() {
        if (window.location.pathname !== "/") {
            return window.location.pathname.indexOf("/my") !== 0;
        } else {
            return false;
        }
    },
    login(view, {username = "", password = "", code = ""}) {
        let loginInfo = this.getUserMap();
        return view.addChild(Loading, {parameter: {content: "正在登录..."}}).then(loading => {
            if (this.isAdmin()) {
                return importScript("/static/sm4.js").then(() => {
                    return view.context.request.post('/api/admin/user/logout').then(() => {
                        return view.context.request.post('/api/admin/user/getToken').then(info => {
                            this.save({token: info.data});
                            return view.context.request.post(loginInfo.loginURL, {
                                userName: username,
                                password: SM4CryptECBWithPKCS7Padding(password, 1, "86C63180C2806ED1F47B859DE501215B"),
                                kaptchaCode: code
                            }).then(a => {
                                if (a.code === '1') {
                                    this.save(Object.assign({token: info.data}, a.data));
                                    loading.showSuccess("登录成功");
                                    loading.close().then(() => {
                                        view.dispatchEvent('gotoPage', loginInfo.indexURL);
                                    });
                                } else {
                                    loading.showError("登录失败" + a.msg);
                                    loading.close().then(() => {
                                        view.dispatchEvent('gotoPage', loginInfo.loginPath);
                                    });
                                }
                            });
                        });
                    });
                });
            } else {
                return importScript("/static/sm4.js").then(() => {
                    return view.context.request.post(loginInfo.loginURL, {
                        userName: username,
                        password: SM4CryptECBWithPKCS7Padding(password, 1, "86C63180C2806ED1F47B859DE501215B"),
                        kaptchaCode: code
                    }).then(a => {
                        if (a.code == 100000) {
                            this.save(a.data);
                            loading.showSuccess("登录成功");
                            loading.close().then(() => {
                                view.dispatchEvent('gotoPage', loginInfo.indexURL);
                            });
                        } else {
                            view.commit("refreshCode");
                            loading.showError("登录失败" + a.msg);
                            loading.close().then(() => {
                                view.dispatchEvent('gotoPage', loginInfo.loginPath);
                            });
                        }
                    });
                });
            }
        });
    },
    getUserNavigator() {
        return this.getIndexMap().navigator;
    },
    getUserFooter() {
        if (window.location.pathname.indexOf("/my") === 0) {
            return MAP.user.footer;
        } else {
            return MAP.admin.footer;
        }
    },
    clean() {
        this.info = {};
        window.localStorage.baseInfo = '{}';
        window.localStorage.pageMap = '{}';
    },
    check(view) {
        let t = this.getBaseInfo();
        if (t.u !== undefined) {
            if (t.admin !== undefined) {
                if (this.isAdmin()) {
                    if (t.admin === false) {
                        this.clean();
                        window.location.href = MAP.admin.loginPath;
                    }
                } else {
                    if (t.admin === true) {
                        view.context.request.post('/api/admin/user/logout').then(() => {
                            this.clean();
                            view.dispatchEvent('gotoPage', MAP.user.loginPath);
                        });
                    }
                }
            }
        }
    }
};

export default User;